/**
 * 
 */
package any.note.server.resource;

import java.io.IOException;
import java.util.Properties;

import net.sf.json.JsonConfig;

import org.apache.commons.lang.Validate;
import org.restlet.data.MediaType;
import org.restlet.resource.Representation;
import org.restlet.resource.Variant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import any.note.Note;
import any.note.server.Bootstrap;
import any.restlet.JSONRepresentation;
import any.restlet.helper.RepresentationHandler;

/**
 * @author keke
 * @version $Revision: 30 $
 */
public class NoteRepresentationHelper implements RepresentationHandler {
	private static final Logger	LOG	= LoggerFactory
	                                        .getLogger(NoteRepresentationHelper.class);
	private JsonConfig	        jsonConfig;

	public void setJsonConfig(final JsonConfig jsonConfig) {
		this.jsonConfig = jsonConfig;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see any.note.server.RepresentationHelper#toEntity(org.restlet.resource.Representation)
	 */
	public Object toEntity(final Representation representation)
	        throws IOException {
		Validate.notNull(representation);
		final MediaType mediaType = representation.getMediaType();
		if (LOG.isDebugEnabled()) {
			LOG.debug("MediaType of representation is {}", mediaType);
		}
		if (mediaType.equals(MediaType.TEXT_PLAIN, true)) {
			final Properties prop = new Properties();
			prop.load(representation.getReader());
			final Note note = new Note();
			note.setUuid(prop.getProperty("uuid"));
			return note;
		}
		return null;
	}

	public Representation toRepresentation(final Object entity,
	        final Variant variant) {
		Validate.notNull(entity, "Entity should not be null");
		Validate.notNull(variant, "Variant should not be null");
		final String type = variant.getMediaType().getName();
		if (type.equals(MediaType.APPLICATION_JSON.getName())) {
			return new JSONRepresentation(entity, jsonConfig, variant
			        .getMediaType());
		} else if (type.equals(Bootstrap.APPLICATION_NOTE.getName())) {
			// TODO: return Note representation;
		}
		return null;
	}
}
